<template>
  <div class="dashboard-container">
    <div class="app-container">
      <page-tools :show-before="true">
        <span slot="before">共{{ page.total }}条记录</span>
        <template slot="after">
          <el-button size="small" type="warning" @click="$router.push('/import')">导入</el-button>
          <el-button v-if="checkPermission('exportEmployee')" size="small" type="danger" @click="exportEmployee">导出</el-button>
          <el-button v-if="checkPermission('addEmployee')" size="small" type="primary" @click="showDialog=true">新增员工</el-button>
        </template>
      </page-tools>
      <!-- 放置表格和分页 -->
      <el-card>
        <el-table border :data="employeesList">
          <el-table-column label="序号" sortable="" type="index" />
          <el-table-column label="姓名" sortable="" prop="username" />
          <el-table-column label="头像" sortable="" width="200">
            <template #default="{row}">
              <img v-imgerr="require('@/assets/common/head.jpg')" :src="row.staffPhoto" alt="" class="avatar" @click="showCode(row.staffPhoto)">
            </template>
          </el-table-column>
          <el-table-column label="工号" sortable="" prop="workNumber" />
          <el-table-column label="聘用形式" sortable="" prop="formOfEmployment" :formatter="formatEmployment" />
          <el-table-column label="部门" sortable="" prop="departmentName" />
          <el-table-column label="入职时间" sortable="">
            <template #default="{row}">
              {{ row.timeOfEntry | formatDate }}
            </template>
          </el-table-column>
          <el-table-column label="账户状态" sortable="">
            <template #default="{row}">
              <el-switch :value="row.enableState===1" />
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template #default="{row}">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="showRoleDialog(row.id)">角色</el-button>
              <el-button type="text" size="small" @click="delEmployee(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination layout="prev, pager, next" :total="page.total" :page-size="page.size" @current-change="currentChange" />
        </el-row>
      </el-card>
      <AddEmployees :show-dialog="showDialog" />
      <el-dialog :visible="isShowCode" @close="isShowCode=false">
        <el-row type="flex" justify="center">
          <canvas ref="qrCode" />
        </el-row>
      </el-dialog>
      <AssignRole ref="assignRole" :show-dialog.sync="isShowRoleDialog" />
    </div>
  </div>
</template>

<script>
import { getEmployee, delEmployee } from '@/api/employees'
import emoloyyessEnum from '@/api/constant/employees'
import { export_json_to_excel } from '@/vendor/Export2Excel'
import { formatDate } from '@/filters'
import AddEmployees from './components/AddEmployees'
import QRCode from 'qrcode'
import AssignRole from './components/AssignRole'
export default {
  components: {
    AddEmployees,
    AssignRole
  },
  data() {
    return {
      page: {
        page: 1,
        size: 5,
        total: 0
      },
      employeesList: [],
      showDialog: false,
      isShowCode: false,
      isShowRoleDialog: false
    }
  },
  created() {
    this.getEmployee()
  },
  methods: {
    // 删除员工点击事件
    async delEmployee(id) {
      console.log(id)
      await this.$confirm('是否确认删除')
      const res = await delEmployee(id)
      console.log(res)
      this.$message.success('删除成功')
      if (this.page.page > 1 && this.employeesList.length === 1) {
        this.page.page--
      }
      this.getEmployee()
    },
    // 导出员工点击事件
    async exportEmployee() {
      const { rows } = await getEmployee({ page: 1, size: this.page.total })
      console.log(rows)
      const header = [
        '手机号',
        '姓名',
        '入职日期',
        '聘用形式',
        '转正日期',
        '工号',
        '部门'
      ]
      const data = rows.map(userObj => {
        return this.obj2arr(userObj, header)
      })
      export_json_to_excel({
        header,
        data
      })
    },
    // 对象转数组
    obj2arr(userObj, header) {
      const dict = {
        '手机号': 'mobile',
        '姓名': 'username',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
      const userArr = []
      header.forEach(key => {
        const enKey = dict[key]
        // 处理数据格式
        if (enKey === 'formOfEmployment') { // 聘用形式
          const obj = emoloyyessEnum.hireType.find(item => item.id === userObj[enKey]) // 使用枚举的函数
          userArr.push(obj ? obj.value : '未知形式')
        } else if (enKey === 'timeOfEntry' || enKey === 'correctionTime') { // 处理时间
          userArr.push(formatDate(userObj[enKey])) // 引入过滤器的函数
        } else {
          userArr.push(userObj[enKey])
        }
      })
      return userArr
    },
    // 获取员工详细列表
    async getEmployee() {
      const { rows, total } = await getEmployee(this.page)
      this.employeesList = rows
      this.page.total = total
    },
    // 分页点击事件
    currentChange(newPage) {
      this.page.page = newPage
      // 刷新页面
      this.getEmployee()
    },
    // 过滤聘用形式数据
    formatEmployment(row, column, cellValue, index) {
      const result = emoloyyessEnum.hireType.find(item => item.id === cellValue)
      return result ? result.value : '未知'
    },
    // 点击头像显示二维码
    showCode(url) {
      if (url) {
        this.isShowCode = true
        this.$nextTick(() => {
          QRCode.toDataURL(this.$refs.qrCode, url)
        })
      }
    },
    // 角色点击事件
    async showRoleDialog(id) {
      await this.$refs.assignRole.getCheckedRole(id)
      this.isShowRoleDialog = true
    }
  }
}
</script>

<style lang="scss" scoped>
.avatar {
  border-radius: 50px;
  width: 100px;
  height: 100px;
  object-fit: cover;
}
</style>
